#include "stdafx.h"
#include "NtVO_Mesh.h"
#include "NtApplication.h"

NtVO_Mesh::NtVO_Mesh(void)
: m_pMesh(NULL)
{
}

NtVO_Mesh::~NtVO_Mesh(void)
{
}

void NtVO_Mesh::Render()
{
	if ( m_pMesh && GetVisible())
	{
		LPDIRECT3DDEVICE9 Device = NtApplication::GetInstance()->GetDevice();
		for(unsigned int i=0; i<m_MaterialVector.size(); ++i)
		{
			LPDIRECT3DTEXTURE9 Tex= NULL;
			if ( m_MaterialVector[i].m_Texture)
			{
				Tex = (*(m_MaterialVector[i].m_Texture));
			}

			Device->SetMaterial( &m_MaterialVector[i].m_Material);

			Device->SetTexture(0, Tex);

			m_pMesh->DrawSubset(i);
		}
	}
}

void NtVO_Mesh::Update( DWORD dwTimer )
{

}


void NtVO_Mesh::ResetMesh()
{
}

BOOL NtVO_Mesh::LoadX( const char* szXFile )
{
	if (! szXFile)
	{
		return FALSE;
	}

	LPD3DXBUFFER AjacencyBuffer = NULL;
	LPD3DXBUFFER MaterialBuffer = NULL;
	DWORD dwMaterialNum;

	HRESULT hr;
	hr = D3DXLoadMeshFromX( szXFile, 
		D3DXMESH_MANAGED, 
		NtApplication::GetInstance()->GetDevice(), 
		&AjacencyBuffer, 
		&MaterialBuffer, 
		NULL, 
		&dwMaterialNum, 
		&m_pMesh);

	if (FAILED(hr))
	{
		return FALSE;
	}

	if (MaterialBuffer && dwMaterialNum> 0)
	{
		D3DXMATERIAL* pMaterials = (D3DXMATERIAL*)
			MaterialBuffer->GetBufferPointer();
		
		for(DWORD i =0; i< dwMaterialNum; ++i)
		{
			NtD3DMaterial9 Material;
			Material.m_Material = pMaterials[i].MatD3D;

			Material.m_Material.Ambient.a = 0;
			Material.m_Material.Ambient.r = 0;
			Material.m_Material.Ambient.g = 0;
			Material.m_Material.Ambient.b = 0;

			Material.m_Material.Emissive.a = 0;
			Material.m_Material.Emissive.r = 0;
			Material.m_Material.Emissive.g = 0;
			Material.m_Material.Emissive.b = 0;

			Material.m_Material.Specular.a = 0;
			Material.m_Material.Specular.r = 0;
			Material.m_Material.Specular.g = 0;
			Material.m_Material.Specular.b = 0;

			Material.m_Material.Diffuse.a = 1;
			Material.m_Material.Diffuse.r = 1;
			Material.m_Material.Diffuse.g = 1;
			Material.m_Material.Diffuse.b = 1;

			Material.m_Material.Power= 2.0f;

			Material.m_Texture =new NtD3DTexture9;
			Material.m_Texture->LoadTexture( pMaterials[i].pTextureFilename);
			m_MaterialVector.push_back(Material);
		}
	}

	hr = m_pMesh->OptimizeInplace(D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_COMPACT | D3DXMESHOPT_VERTEXCACHE,
		(DWORD*) AjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL);

	if (FAILED(hr))
	{
		return FALSE;
	}

	NtRelease(AjacencyBuffer);
	NtRelease(MaterialBuffer);

	return TRUE;
}
